package workforecast

import org.springframework.dao.DataIntegrityViolationException

class UserController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        redirect(action: "login", params: params)
    }
	
	
	def dologin() {
		
		String pw = params.password
		def u = User.findByUsername(params.username)
		
		session.putAt("me", u.id );
			
		if (pw == u.password) {
			redirect(action:"home", params: [idi: u.id.toString()])
		}
		else {
			System.out.println("Wrong");
			render(view: "loginErrorPassword", model: User)
		}
	}
	
	def login() {
		render (view:"login", model:User)
	}
	
	def logout() {
		String name = User.get(session.getAttribute("me")).username
		session.removeAttribute("me")
		[name:name]
	}
	
	def home() {
		def id = session.getAttribute("me");
		def user = User.get(id);
		
		def action = user.role.name.equals("Consultant") ? "create" : "list"
		
		def fId = null
		if (user.role.name.equals("Consultant")) {
			def forecasts = Forecast.findAllWhere(user: user)
			
			if (!forecasts.isEmpty()) {
				int latestDate = 0		// Date = YYYYWW
				def latestForecast
				
				// Search latest forecast by comparing end dates
				for (int i = 0; i < forecasts.size(); i++) {
					int date = forecasts.get(i).endYear * 100 + forecasts.get(i).endWeek
					if (date > latestDate) {
						latestDate = forecasts.get(i).endYear * 100 + forecasts.get(i).endWeek
						latestForecast = forecasts.get(i)
					}
				}
				
				action = "show"
				fId = latestForecast.id
			}
		}
		
		def permissions = [
			showForecastSection: user.role.name.equals("Consultant") || user.role.name.equals("Manager"),
			showReportSection: user.role.name.equals("Director") || user.role.name.equals("Manager"),
			showManagementSection: user.role.name.equals("Director") || user.role.name.equals("Manager"),
			
			forecastAction: action,
			forecastId: fId
		]
		
		[userInstance:User.get(id), userName:user.username, permissions:permissions]
	}
	
	def managementOverview() {
		
		def user = User.get(session.getAttribute("me"));
		
		def permissions = [
			showBusinessUnitSection: user.role.name.equals("Director"),
			showTeamSection: user.role.name.equals("Director") || user.role.name.equals("Manager"),
			showUserSection: user.role.name.equals("Director") || user.role.name.equals("Manager"),
			showActivityTypeSection: user.role.name.equals("Manager")
		]
		
		[permissions: permissions]
	}

    def list(Integer max) {
        params.max = Math.min(max ?: 10, 100)
		
        [userInstanceList: User.list(params), userInstanceTotal: User.count()]
    }

    def create() {
         [userInstance: new User(params)]
    }

    def save() {
        def userInstance = new User(params)
        if (!userInstance.save(flush: true)) {
            render(view: "create", model: [userInstance: userInstance])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), userInstance.id])
        redirect(action: "show", id: userInstance.id)
    }

    def show(Long id) {
        def userInstance = User.get(id)
        if (!userInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), id])
            redirect(action: "list")
            return
        }

        [userInstance: userInstance]
    }

    def edit(Long id) {
        def userInstance = User.get(id)
        if (!userInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), id])
            redirect(action: "list")
            return
        }

        [userInstance: userInstance]
    }

    def update(Long id, Long version) {
        def userInstance = User.get(id)
        if (!userInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), id])
            redirect(action: "list")
            return
        }

        if (version != null) {
            if (userInstance.version > version) {
                userInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'user.label', default: 'User')] as Object[],
                          "Another user has updated this User while you were editing")
                render(view: "edit", model: [userInstance: userInstance])
                return
            }
        }

        userInstance.properties = params

        if (!userInstance.save(flush: true)) {
            render(view: "edit", model: [userInstance: userInstance])
            return
        }

        flash.message = message(code: 'default.updated.message', args: [message(code: 'user.label', default: 'User'), userInstance.id])
        redirect(action: "show", id: userInstance.id)
    }

    def delete(Long id) {
        def userInstance = User.get(id)
        if (!userInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), id])
            redirect(action: "list")
            return
        }

        try {
            userInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'user.label', default: 'User'), id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'user.label', default: 'User'), id])
            redirect(action: "show", id: id)
        }
    }
}
